package com.arpa.oms.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.collection.IterUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.arpa.ntocc.common.common.cache.PartyCache;
import com.arpa.ntocc.common.common.cache.PartyGroupCache;
import com.arpa.ntocc.common.common.exception.ServiceException;
import com.arpa.ntocc.common.common.util.CommonUtil;
import com.arpa.ntocc.common.common.util.UserUtil;
import com.arpa.oms.domain.dto.OmsInboundDTO;
import com.arpa.oms.domain.dto.OmsInboundItemDTO;
import com.arpa.oms.domain.entity.*;
import com.arpa.oms.domain.enums.OmsInboundTypeEnum;
import com.arpa.oms.domain.enums.PurchaseTypeEnum;
import com.arpa.oms.domain.vo.OmsInboundItemVO;
import com.arpa.oms.domain.vo.OmsInboundVO;
import com.arpa.oms.mapper.OmsInboundMapper;
import com.arpa.oms.mapper.PurchaseItemMapper;
import com.arpa.oms.mapper.PurchaseMapper;
import com.arpa.oms.service.IOmsInboundItemService;
import com.arpa.oms.service.IOmsInboundService;
import com.arpa.oms.service.IOmsInventoryService;
import com.arpa.oms.service.IOmsPayableDetailService;
import com.arpa.wms.cache.WarehouseCache;
import com.arpa.wms.cache.WarehouseShipmentCache;
import com.arpa.wms.common.util.OrderIdGeneratorUtil;
import com.arpa.wms.domain.entity.*;
import com.arpa.wms.domain.enums.InboundStatusEnum;
import com.arpa.wms.domain.enums.ReceiveTypeEnum;
import com.arpa.wms.service.IInboundItemService;
import com.arpa.wms.service.IPutawayItemService;
import com.arpa.wms.service.IReceiveService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.arpa.wms.domain.consts.NumConst.NUM_ONE;
import static com.arpa.wms.domain.consts.NumConst.NUM_ZERO;

/**
 * <p>
 * OMS入库单服务实现类
 * </p>
 *
 * @author LEO
 * @since 2020-10-22
 */
@Service("OmsInboundService")
@Log4j2(topic = "business")
public class OmsInboundServiceImpl extends ServiceImpl<OmsInboundMapper, OmsInbound> implements IOmsInboundService {


    @Resource
    private PurchaseItemMapper purchaseItemMapper;
    @Resource
    private PurchaseMapper purchaseMapper;

    private final PartyCache partyCache;

    private final IInboundItemService iInboundItemService;

    private final IOmsInboundItemService iOmsInboundItemService;

    private final IOmsInventoryService iOmsInventoryService;


    private final IOmsPayableDetailService iOmsPayableDetailService;

    private final WarehouseCache warehouseCache;

    private final PartyGroupCache partyGroupCache;
    @Autowired
    private WarehouseShipmentCache warehouseShipmentCache;

    private final IPutawayItemService putawayItemService;

    private final IReceiveService iReceiveService;


    public OmsInboundServiceImpl(PartyCache partyCache,
                                 IInboundItemService iInboundItemService,
                                 IOmsInboundItemService iOmsInboundItemService,
                                 IOmsInventoryService iOmsInventoryService,
                                 IOmsPayableDetailService iOmsPayableDetailService,
                                 PartyGroupCache partyGroupCache,
                                 WarehouseCache warehouseCache,
                                 IPutawayItemService putawayItemService, IReceiveService iReceiveService) {
        this.partyCache = partyCache;
        this.iInboundItemService = iInboundItemService;
        this.iOmsInboundItemService = iOmsInboundItemService;
        this.iOmsInventoryService = iOmsInventoryService;
        this.iOmsPayableDetailService = iOmsPayableDetailService;
        this.warehouseCache = warehouseCache;
        this.partyGroupCache = partyGroupCache;
        this.putawayItemService = putawayItemService;
        this.iReceiveService = iReceiveService;
    }

    /**
     * 根据WMS入库单生成OMS入库单
     * 回写OMS采购单
     *
     * @param inbound
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveByWmsInbound(Inbound inbound) {
        Receive receive = iReceiveService.getOne(new QueryWrapper<Receive>().lambda().select(Receive::getSourceCode).eq(Receive::getCode, inbound.getSourceCode()));
        Purchase purchase = purchaseMapper.selectOne(new QueryWrapper<Purchase>().lambda().eq(Purchase::getCode, receive.getSourceCode()));
        if(ObjectUtil.isNull(purchase)){
            log.error("找不到采购单");
            return;
        }
        String createdCode = UserUtil.getCode();
        String createdName = partyCache.translate(createdCode);

        //WMS入库单明细
        List<InboundItem> inboundItems = iInboundItemService.list(new QueryWrapper<InboundItem>().lambda().eq(InboundItem::getInboundCode, inbound.getCode()));
        //按商品分组合
        Map<String, List<InboundItem>> listMap = inboundItems.stream().collect(Collectors.groupingBy(InboundItem::getGoodsCode));



        /*创建OMS入库单*/
        //OMS入库单主单
        OmsInbound omsInbound =generateInboundByWms(inbound, createdCode, createdName);
        save(omsInbound);
        //OMS入库单明细
        List<OmsInboundItem> omsInboundItemList = new ArrayList<>();
        iOmsInboundItemService.saveBatch(omsInboundItemList);

        //TODO 生成OMS应付
        //OmsPayableDetail omsPayableDetail = new OmsPayableDetail();
        //omsPayableDetail.setCode(IdUtil.simpleUUID());
        //omsPayableDetail.setShipmentCode(omsInbound.getShipmentCode());
        //omsPayableDetail.setShipmentName(omsInbound.getShipmentName());
        //omsPayableDetail.setSourceCode(omsInbound.getCode());
        //omsPayableDetail.setBillType(PurchaseTypeEnum.NORMAL);
        //omsPayableDetail.setGmtBill(omsInbound.getGmtCreated().toLocalDate().toString());
        //omsPayableDetail.setSupplierCode(purchase.getSupplierCode());
        //omsPayableDetail.setUnsettledMoney(omsInbound.getOwedAmount());
        //omsPayableDetail.setThisSettledMoney(omsInbound.getOwedAmount());
        //omsPayableDetail.setSettledMoney(omsInbound.getPaymentAmount());
        //
        //if(omsInbound.getPaymentAmount()!=null&&omsInbound.getPaymentAmount().compareTo(BigDecimal.ZERO)>0){
        //    omsPayableDetail.setStatus(SettlementStatusEnum.PARTIALLY_SETTLED);
        //}else{
        //    omsPayableDetail.setStatus(SettlementStatusEnum.UNSETTLED);
        //}
        //
        //
        //
        //iOmsPayableDetailService.save(omsPayableDetail);



        // 回写OMS采购单, OMS采购单明细
        List<PurchaseItem> purchaseItems = purchaseItemMapper.selectList(new QueryWrapper<PurchaseItem>().lambda().eq(PurchaseItem::getPurchaseCode, receive.getSourceCode()));
        if(IterUtil.isEmpty(purchaseItems)){
            log.error("生成入库单失败，采购单【{}】异常，采购明细找不到",inbound.getSourceCode());
            throw new ServiceException("生成入库单失败，采购单【"+inbound.getSourceCode()+"】异常，采购明细找不到");
        }
        purchaseItems.forEach(p->{
            List<InboundItem> itemList = listMap.get(p.getGoodsCode());
            if(IterUtil.isEmpty(itemList)){
                log.error("生成入库单失败，采购商品【{}】找不到对应的WMS入库明细",p.getGoodCode());
                throw new ServiceException("生成入库单失败，采购商品【"+p.getGoodCode()+"】找不到对应的WMS入库明细");
            }
            //商品实际入库数量
            BigDecimal inboundQuantity = itemList.stream().map(InboundItem::getInboundQuantity).reduce(BigDecimal.ZERO, BigDecimal::add);
            p.setStorageQuantity(inboundQuantity);
            BigDecimal actualQuantity =  inboundQuantity.divide(p.getUnitConvertQuantity(),6, BigDecimal.ROUND_HALF_UP);
            p.setActualQuantity(actualQuantity);
            BigDecimal totalMoney = inboundQuantity.multiply(p.getTaxUnitPrice());
            p.setTotalMoney(totalMoney);
            //更新采购明细
            purchaseItemMapper.updateById(p);
        });


        //计算采购单明细实际采购数量和
        BigDecimal purchaseActualQuantity =  purchaseItems.stream().map(PurchaseItem::getActualQuantity).reduce(BigDecimal.ZERO, BigDecimal::add);
        //更新采购单实际采购数量
        purchase.setActualQuantity(purchaseActualQuantity);
        //计算采购明细价税合计之和
        BigDecimal purchaseTotalMoney =  purchaseItems.stream().map(PurchaseItem::getTotalMoney).reduce(BigDecimal.ZERO, BigDecimal::add);

        //计算采购单实际欠款
        BigDecimal owedAmount = purchaseTotalMoney.subtract(purchase.getPaymentAmount());
        purchase.setOwedAmount(owedAmount);
        //更新采购单
        purchaseMapper.updateById(purchase);



        /*更新OMS库存*/
        purchaseItems.forEach(item->{
            if(ObjectUtil.isNotNull(item)) {
                OmsInventory sameInv = iOmsInventoryService.hasSameInventory(item.getGoodsCode(), inbound.getWarehouseCode(), inbound.getShipmentCode());
                if (ObjectUtil.isNotNull(sameInv)) {
                    //计算费用
                    //移动加权平均单价= (库存数量*库存价+本次入库金额)/(本次入库前结存数量+本次入库数量)；
                    iOmsInventoryService.update(new UpdateWrapper<OmsInventory>().lambda().eq(OmsInventory::getCode, sameInv.getCode())
                            .setSql(" quantity = quantity + " + item.getActualQuantity())
                            .setSql(" average_unit_price = (total_amount+"+item.getTotalMoney()+")/quantity")
                            .setSql(" total_amount = average_unit_price * quantity")
                    );
                } else {
                    sameInv = new OmsInventory();
                    sameInv.setCode(IdUtil.simpleUUID());
                    sameInv.setShipmentCode(inbound.getShipmentCode());
                    sameInv.setShipmentName(inbound.getShipmentName());
                    sameInv.setWarehouseCode(inbound.getWarehouseCode());
                    sameInv.setGoodCode(item.getGoodCode());
                    sameInv.setGoodsCode(item.getGoodsCode());
                    sameInv.setGoodsName(item.getGoodsName());
                    sameInv.setGoodsBarCode(item.getGoodsBarCode());
                    sameInv.setSpec(item.getSpec());
                    sameInv.setBasicUnit(item.getBasicUnit());
                    sameInv.setBasicUnitName(item.getBasicUnitName());
                    sameInv.setQuantity(item.getActualQuantity());
                    sameInv.setAverageUnitPrice(item.getUnitPrice());
                    sameInv.setTotalAmount(item.getTotalMoney());
                    sameInv.setCreatedBy(UserUtil.getCode());
                    sameInv.setCreatedName(partyCache.translate(UserUtil.getCode()));
                    sameInv.setModifiedBy(UserUtil.getCode());
                    sameInv.setCreatedName(partyCache.translate(UserUtil.getCode()));
                    iOmsInventoryService.save(sameInv);
                }
            }
        });

        //更新金额和单价
    }

    /**
     * 根据wms入库单生成oms的入库单
     * @param inbound
     * @param createdCode
     * @param createdName
     * @return
     */
    private OmsInbound generateInboundByWms(Inbound inbound, String createdCode, String createdName) {
        OmsInbound inOutbound = new OmsInbound();
        BeanUtil.copyProperties(inbound, inOutbound);
        inOutbound.setCode(OrderIdGeneratorUtil.generatorOmsOrderId(OrderIdGeneratorUtil.OrderTypeEnum.CK, inbound.getShipmentCode(),UserUtil.getBranchCode()));
        inOutbound.setType(ReceiveTypeEnum.RECEIVE.getValue());
        inOutbound.setStatus("1");
        inOutbound.setRemarks(StrUtil.EMPTY);
        inOutbound.setCreatedBy(createdCode);
        inOutbound.setCreatedName(createdName);
        inOutbound.setModifiedName(StrUtil.EMPTY);
        inOutbound.setModifiedBy(StrUtil.EMPTY);
        inOutbound.setGmtModified(null);
        return inOutbound;
    }


    @Override
    public int updateByCode(OmsInbound entity) {
        if(StringUtils.isBlank(entity.getModifiedBy())){
            entity.setModifiedBy(UserUtil.getCode());
            entity.setModifiedName(partyCache.translate(UserUtil.getCode()));
        }
        return baseMapper.update(entity,new QueryWrapper<OmsInbound>().lambda().eq(OmsInbound::getCode,entity.getCode()));
    }

    @Override
    public List<OmsInboundVO> queryList(OmsInboundDTO omsInboundDTO) {
        //排序字段名需要驼峰转数据库下划线类型字段名
        if(StringUtils.isNotEmpty(omsInboundDTO.getSortField())){
            omsInboundDTO.setSortField(CommonUtil.camel2Underline(omsInboundDTO.getSortField()));
        }
        List<OmsInboundVO> omsInboundVOList = baseMapper.queryList(omsInboundDTO);
        omsInboundVOList.stream().forEach(info ->{
            info.setWarehouseName(warehouseCache.translate(info.getWarehouseCode()));
            info.setTypeText(PurchaseTypeEnum.translate(info.getType()));
            info.setStatusText(InboundStatusEnum.translate(info.getStatus()));
        });
        return omsInboundVOList;
    }

    @Override
    public OmsInboundVO queryListSum(OmsInboundDTO omsInboundDTO) {
        OmsInboundVO omsInboundVO = baseMapper.queryListSum(omsInboundDTO);
        return omsInboundVO;
    }

    @Override
    public OmsInboundVO getVOByCode(String code) {
        OmsInbound entity = this.getOne(new QueryWrapper<OmsInbound>().lambda().eq(OmsInbound::getCode, code));
        OmsInboundVO vo = new OmsInboundVO();
        BeanUtil.copyProperties(entity, vo);
        // 翻译
        vo.setTypeText(PurchaseTypeEnum.translate(vo.getType()));
        vo.setGroupName(partyGroupCache.translate(vo.getGroupCode()));

        OmsInboundItemDTO itemDTO = new OmsInboundItemDTO();
        itemDTO.setInboundCode(vo.getCode());
        itemDTO.setPageSize(Integer.MAX_VALUE);
        List<OmsInboundItemVO> itemVOS = iOmsInboundItemService.queryList(itemDTO);
        vo.setOmsInboundItemVOList(itemVOS);
        vo.setWarehouseName(warehouseCache.translate(vo.getWarehouseCode()));
        return vo;
    }
    //上架单putaway主要用来回显入库数据的
    @Override
    public void saveByOmsAllocation(OmsAllocation omsAllocation,Putaway putaway) {
        OmsInbound omsInbound = new OmsInbound();
        BeanUtils.copyProperties(omsAllocation, omsInbound);
        omsInbound.setCode(OrderIdGeneratorUtil.generatorOmsOrderId(OrderIdGeneratorUtil.OrderTypeEnum.RK, "",UserUtil.getBranchCode()));
        omsInbound.setWarehouseCode(omsAllocation.getTargetWarehouseCode());
        omsInbound.setSourceCode(omsAllocation.getCode());
        omsInbound.setStatus(InboundStatusEnum.FINISH_IN.getValue());
        omsInbound.setType(PurchaseTypeEnum.ALLOCATION.getValue());
        omsInbound.setCreatedBy(UserUtil.getCode());
        omsInbound.setCreatedName(partyCache.translate(UserUtil.getCode()));
        omsInbound.setGmtCreated(LocalDateTime.now());

        save(omsInbound);

        List<OmsInboundItem> omsInboundItemList = CollectionUtil.newArrayList();
        if (ObjectUtil.isNotNull(putaway)) {
            List<PutawayItem> putawayItems = putawayItemService.list(new QueryWrapper<PutawayItem>().lambda().eq(PutawayItem::getPutawayCode,putaway.getCode()));
            for (OmsAllocationItem omsAllocationItem : omsAllocation.getAllocationItemList()) {
                for (PutawayItem putawayItem : putawayItems) {
                    if (omsAllocationItem.getCode().equals(putawayItem.getSourceItemCode())) {
                        //调拨单生成的入库单  单价和含税单价 一样，都用调拨单的平均价表示
                        BigDecimal unitPrice = omsAllocationItem.getAverageUnitPrice();
                        BigDecimal storageQuantity = putawayItem.getPutawayQuantity();
                        //调拨单生成的入库单  由于税率为0，金额和价税合计 一样，都采用 amountMoney 的值
                        BigDecimal amountMoney = unitPrice.multiply(storageQuantity).setScale(6, BigDecimal.ROUND_HALF_UP);
                        OmsInboundItem omsInboundItem = new OmsInboundItem();
                        BeanUtils.copyProperties(omsAllocationItem, omsInboundItem);
                        omsInboundItem.setCode(IdUtil.simpleUUID());
                        omsInboundItem.setInboundCode(omsInbound.getCode());
                        omsInboundItem.setStorageQuantity(putawayItem.getPutawayQuantity());
                        omsInboundItem.setCreatedBy(UserUtil.getCode());
                        omsInboundItem.setCreatedName(partyCache.translate(UserUtil.getCode()));
                        omsInboundItem.setGmtCreated(LocalDateTime.now());

                        omsInboundItem.setTaxRate(BigDecimal.ZERO);
                        omsInboundItem.setUnitPrice(unitPrice);
                        omsInboundItem.setTaxUnitPrice(unitPrice);
                        omsInboundItem.setAmountMoney(amountMoney);
                        omsInboundItem.setTaxMoney(BigDecimal.ZERO);
                        omsInboundItem.setTotalMoney(amountMoney);

                        omsInboundItemList.add(omsInboundItem);
                    }
                }
            }
        } else {
            omsAllocation.getAllocationItemList().stream().forEach(item -> {

                //入库明细数量大于0时，才进行数据回显
                if (item.getInboundQuantity().compareTo(BigDecimal.ZERO)>0){
                    //调拨单生成的入库单  单价和含税单价 一样，都用调拨单的平均价表示
                    BigDecimal unitPrice = item.getAverageUnitPrice();
                    BigDecimal storageQuantity = item.getInboundQuantity();
                    //调拨单生成的入库单  由于税率为0，金额和价税合计 一样，都采用 amountMoney 的值
                    BigDecimal amountMoney = unitPrice.multiply(storageQuantity).setScale(6, BigDecimal.ROUND_HALF_UP);

                    OmsInboundItem omsInboundItem = new OmsInboundItem();
                    BeanUtils.copyProperties(item, omsInboundItem);
                    omsInboundItem.setCode(IdUtil.simpleUUID());
                    omsInboundItem.setInboundCode(omsInbound.getCode());
                    omsInboundItem.setStorageQuantity(storageQuantity);
                    omsInboundItem.setCreatedBy(UserUtil.getCode());
                    omsInboundItem.setCreatedName(partyCache.translate(UserUtil.getCode()));
                    omsInboundItem.setGmtCreated(LocalDateTime.now());

                    omsInboundItem.setTaxRate(BigDecimal.ZERO);
                    omsInboundItem.setUnitPrice(unitPrice);
                    omsInboundItem.setTaxUnitPrice(unitPrice);
                    omsInboundItem.setAmountMoney(amountMoney);
                    omsInboundItem.setTaxMoney(BigDecimal.ZERO);
                    omsInboundItem.setTotalMoney(amountMoney);


                    omsInboundItemList.add(omsInboundItem);
                }
            });
        }


        iOmsInboundItemService.saveBatch(omsInboundItemList);

        omsInboundItemList.forEach(r -> {
            OmsInventory inventory = iOmsInventoryService.getOne(new QueryWrapper<OmsInventory>().lambda().eq(OmsInventory::getGoodsCode, r.getGoodsCode())
                    .eq(OmsInventory::getWarehouseCode, omsInbound.getWarehouseCode())
                    .eq(OmsInventory::getShipmentCode, omsInbound.getShipmentCode()));
            if (ObjectUtil.isNotNull(inventory)) {
                //更新库存
                if (null == r.getTotalMoney()) {
                    r.setTotalMoney(new BigDecimal("0"));
                }
                iOmsInventoryService.update(new UpdateWrapper<OmsInventory>().lambda()
                        .eq(OmsInventory::getWarehouseCode, omsInbound.getWarehouseCode())
                        .eq(OmsInventory::getShipmentCode, omsInbound.getShipmentCode())
                        .eq(OmsInventory::getGoodsCode, r.getGoodsCode())
                        .setSql("quantity=quantity+" + r.getStorageQuantity())
                        .setSql("average_unit_price = (total_amount+"+r.getTotalMoney()+")/quantity")
                        .setSql("total_amount = average_unit_price * quantity")
                );
            } else {
                //新增
                inventory = new OmsInventory();
                BeanUtil.copyProperties(r, inventory, false);
                inventory.setShipmentCode(omsInbound.getShipmentCode());
                inventory.setShipmentName(omsInbound.getShipmentName());
                inventory.setWarehouseCode(omsInbound.getWarehouseCode());
                inventory.setCode(IdUtil.simpleUUID());
                inventory.setQuantity(r.getStorageQuantity());
                inventory.setAverageUnitPrice(r.getUnitPrice());
                //总价格=数量*单价
                if (ObjectUtil.isNotNull(r.getUnitPrice())) {
                    BigDecimal totalAmount = inventory.getAverageUnitPrice().multiply(r.getStorageQuantity());
                    inventory.setTotalAmount(totalAmount);
                }
                inventory.setCreatedBy(UserUtil.getCode());
                inventory.setCreatedName(partyCache.translate(UserUtil.getCode()));
                inventory.setModifiedBy(UserUtil.getCode());
                inventory.setCreatedName(partyCache.translate(UserUtil.getCode()));
                iOmsInventoryService.save(inventory);
            }
        });
    }

    @Override
    public void saveByWmsInbound(Inbound inbound, List<InboundItem> inboundItemList) {
        List<WarehouseShipment> warehouseShipmentCacheList = warehouseShipmentCache.getObjList(inbound.getWarehouseCode());
        List<WarehouseShipment> warehouseShipmentList = warehouseShipmentCacheList.stream().filter(item -> item.getShipmentCode().equals(inbound.getShipmentCode())).collect(Collectors.toList());
        if (IterUtil.isNotEmpty(warehouseShipmentList) && warehouseShipmentList.get(NUM_ZERO).getUseOms().equals(NUM_ONE)) {
            OmsInbound omsInbound = new OmsInbound();
            BeanUtils.copyProperties(inbound, omsInbound);
            omsInbound.setCode(OrderIdGeneratorUtil.generatorOmsOrderId(OrderIdGeneratorUtil.OrderTypeEnum.RK, "",UserUtil.getBranchCode()));
            omsInbound.setSourceCode(inbound.getSourceCode());
            omsInbound.setStatus(InboundStatusEnum.FINISH_IN.getValue());
            switch (inbound.getType()) {
                case "2":
                    omsInbound.setType(OmsInboundTypeEnum.COUNT_SURPLUS.getValue());
                    break;
                case "4":
                    omsInbound.setType(OmsInboundTypeEnum.INITIALIZATION.getValue());
                    break;
                default:
            }
            omsInbound.setCreatedBy(UserUtil.getCode());
            omsInbound.setCreatedName(partyCache.translate(UserUtil.getCode()));
            omsInbound.setGmtCreated(LocalDateTime.now());

            List<OmsInboundItem> omsInboundItemList = inboundItemList.stream().map(item -> {
                OmsInboundItem omsInboundItem = new OmsInboundItem();
                BeanUtils.copyProperties(item, omsInboundItem);
                omsInboundItem.setCode(IdUtil.simpleUUID());
                omsInboundItem.setBasicUnit(item.getBasicUnit());
                omsInboundItem.setBasicUnitName(item.getBasicUnitName());
                omsInboundItem.setInboundCode(omsInbound.getCode());
                omsInboundItem.setStorageQuantity(item.getInboundQuantity());
                omsInboundItem.setCreatedBy(UserUtil.getCode());
                omsInboundItem.setCreatedName(partyCache.translate(UserUtil.getCode()));
                omsInboundItem.setGmtCreated(LocalDateTime.now());

                return omsInboundItem;
            }).collect(Collectors.toList());

            save(omsInbound);
            iOmsInboundItemService.saveBatch(omsInboundItemList);

            omsInboundItemList.forEach(r -> {
                OmsInventory inventory = iOmsInventoryService.getOne(new QueryWrapper<OmsInventory>().lambda().eq(OmsInventory::getGoodsCode, r.getGoodsCode())
                        .eq(OmsInventory::getWarehouseCode, omsInbound.getWarehouseCode())
                        .eq(OmsInventory::getShipmentCode, omsInbound.getShipmentCode()));
                if (ObjectUtil.isNotNull(inventory)) {
                    //更新库存
                    iOmsInventoryService.update(new UpdateWrapper<OmsInventory>().lambda()
                                    .eq(OmsInventory::getWarehouseCode, omsInbound.getWarehouseCode())
                                    .eq(OmsInventory::getShipmentCode, omsInbound.getShipmentCode())
                                    .eq(OmsInventory::getGoodsCode, r.getGoodsCode())
                                    .setSql("quantity=quantity+" + r.getStorageQuantity())
                                    .setSql("average_unit_price = 0")
                                    .setSql("total_amount = 0")
                    );
                } else {
                    //新增
                    inventory = new OmsInventory();
                    BeanUtil.copyProperties(r, inventory, false);
                    inventory.setShipmentCode(omsInbound.getShipmentCode());
                    inventory.setShipmentName(omsInbound.getShipmentName());
                    inventory.setWarehouseCode(omsInbound.getWarehouseCode());
                    inventory.setCode(IdUtil.simpleUUID());
                    inventory.setQuantity(r.getStorageQuantity());
                    inventory.setAverageUnitPrice(BigDecimal.ZERO);
                    inventory.setTotalAmount(BigDecimal.ZERO);
                    inventory.setCreatedBy(UserUtil.getCode());
                    inventory.setCreatedName(partyCache.translate(UserUtil.getCode()));
                    inventory.setModifiedBy(UserUtil.getCode());
                    inventory.setCreatedName(partyCache.translate(UserUtil.getCode()));
                    iOmsInventoryService.save(inventory);
                }
            });
        }
    }


    @Override
    public List<Map<String, Object>> inboundCount(String shipmentCode, List<String> warehouseCodes) {
        return baseMapper.inboundCount(shipmentCode,warehouseCodes);
    }
}
